package com.unlcn.ils.wms.web.controller.inbound;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.zxing.WriterException;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundAllocationBO;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundCheckBO;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundOrderBO;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundOrderDetailBO;
import com.unlcn.ils.wms.backend.dto.inboundDTO.WmsInboundOrderDTO;
import com.unlcn.ils.wms.backend.enums.WmsStatusEnum;
import com.unlcn.ils.wms.backend.service.baseData.WmsLocationService;
import com.unlcn.ils.wms.backend.service.gate.GateControllerService;
import com.unlcn.ils.wms.backend.service.inbound.*;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDetailDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.WmsAsnOrderQueryDTO;
import com.unlcn.ils.wms.base.dto.WmsRecordsImportExcelDTO;
import com.unlcn.ils.wms.web.controller.annotation.LogAnnotation;
import com.unlcn.ils.wms.web.utils.BitMatrixToImageWritter;
import com.unlcn.ils.wms.web.utils.Vo2Bo;
import com.unlcn.ils.wms.web.vo.inbound.WmsInboundAllocationVO;
import com.unlcn.ils.wms.web.vo.inbound.WmsInboundCheckVO;
import com.unlcn.ils.wms.web.vo.inbound.WmsInboundOrderVO;
import com.unlcn.ils.wms.web.vo.inbound.WmsPrintBarcodeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 订单业务：新增、质检、确认入库、打印二维码操作
 * Created by DELL on 2017/8/4.
 */
@Controller
@RequestMapping("/asnOrder")
@ResponseBody
public class WmsInboundOrderController {
    private Logger LOGGER = LoggerFactory.getLogger(WmsInboundOrderController.class);

    @Autowired
    private AsnOrderService asnOrderService;

    @Autowired
    private AsnOrderCheckService asnOrderCheckService;

    @Autowired
    private WmsAllocationService wmsAllocationService;

    @Autowired
    private WmsStrategyService wmsStrategyService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private WmsLocationService wmsLocationService;

    @Autowired
    private WmsInboundAsnService wmsInboundAsnService;

    private GateControllerService gateControllerService;

    @Autowired
    public void setGateControllerService(GateControllerService gateControllerService) {
        this.gateControllerService = gateControllerService;
    }


    @Value("${activemq.host}")
    private String host;
    @Value("${activemq.user}")
    private String userName;
    @Value("${activemq.password}")
    private String password;

    /**
     * 入库作业管理列表查询
     * <p>
     * 2018-1-11 取消入库新功能(重庆库) 调整入库时间显示
     * </p>
     *
     * @param wmsInboundOrderVO 参数封装
     * @return 返回值
     * @throws BusinessException 异常
     */
    @RequestMapping(value = "/getAsnOrderList", method = RequestMethod.POST)
    public ResultDTO<Object> getAsnOrderList(@RequestBody WmsInboundOrderVO wmsInboundOrderVO,
                                             HttpServletRequest request) throws BusinessException {
        LOGGER.info("AsnOrderController.getAsnOrderList param:{}.", wmsInboundOrderVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            WmsAsnOrderQueryDTO wmsAsnOrderQueryDTO = new WmsAsnOrderQueryDTO();
            BeanUtils.copyProperties(wmsInboundOrderVO, wmsAsnOrderQueryDTO);
            resultDTO.setMessage("查询成功");
            resultDTO.setMessageCode("200");
            resultDTO.setSuccess(true);
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            wmsAsnOrderQueryDTO.setOdWhCode(whCode);
            resultDTO.setData(asnOrderService.getListAsnOrderBO(wmsAsnOrderQueryDTO));
        } catch (BusinessException e) {
            LOGGER.error("AsnOrderController.getAsnOrderList BusinessException: {}", e);
            resultDTO.setMessage(e.getMessage());
            resultDTO.setMessageCode("500");
            resultDTO.setSuccess(false);
        } catch (Exception e) {
            LOGGER.error("AsnOrderController.getAsnOrderList error: {}", e);
            resultDTO.setMessage("查询异常");
            resultDTO.setMessageCode("500");
            resultDTO.setSuccess(false);
        }
        return resultDTO;
    }

    /**
     * 新增收货单
     *
     * @param wmsInboundOrderVO
     * @return
     */
    @RequestMapping(value = "/addAsnOrder", method = RequestMethod.POST)
    @LogAnnotation(methods = "入库管理", modules = "手工新增订单")
    public ResultDTO addAsnOrder(@RequestBody WmsInboundOrderVO wmsInboundOrderVO) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            wmsInboundOrderVO.setOdStatus(String.valueOf(WmsStatusEnum.WMS_INBOUND_CREATE.getValue()));
            WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
            BeanUtils.copyProperties(wmsInboundOrderVO, wmsInboundOrderBO);
            wmsInboundOrderBO.setIsDeleted((byte) 1);
            boolean result = asnOrderService.saveAsnOrder(wmsInboundOrderBO);
            if (result) {
                resultDTO.setMessage("创建订单成功!");
                resultDTO.setSuccess(true);
                resultDTO.setMessageCode("200");
                return resultDTO;
            } else {
                resultDTO.setMessage("创建订单失败");
                resultDTO.setSuccess(false);
                resultDTO.setMessageCode("500");
                return resultDTO;
            }
        } catch (BeansException ex) {
            LOGGER.error("AsnOrderController.addAsnOrder error: {}", ex);
            throw new BusinessException(ex);
        }
    }

    /**
     * 根据id获取数据
     *
     * @param odId
     * @return
     */
    @RequestMapping(value = "/getAsnOrderById/{odId}")
    public ResultDTO getAsnOrderById(@PathVariable("odId") String odId) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            WmsInboundOrderBO wmsInboundOrderBO = asnOrderService.getAsnOrderById(odId);
            resultDTO.setMessage("查询订单成功!");
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            resultDTO.setData(wmsInboundOrderBO);
            return resultDTO;
        } catch (BusinessException ex) {
            LOGGER.error("AsnOrderController.getAsnOrderById error: {}", ex);
            resultDTO.setMessage("查询订单失败!");
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            return resultDTO;
        }

    }

    /**
     * 修改订单
     *
     * @param wmsInboundOrderVO
     * @return
     */
    @RequestMapping(value = "/updateAsnOrder", method = RequestMethod.POST)
    @LogAnnotation(methods = "入库管理", modules = "修改手工新增订单")
    public ResultDTO updateAsnOrder(@RequestBody WmsInboundOrderVO wmsInboundOrderVO) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
            BeanUtils.copyProperties(wmsInboundOrderVO, wmsInboundOrderBO);
            boolean result = asnOrderService.updateAsnOrderByEntity(wmsInboundOrderBO);
            if (result) {
                resultDTO.setMessage("修改订单成功!");
                resultDTO.setSuccess(true);
                resultDTO.setMessageCode("200");
                return resultDTO;
            } else {
                resultDTO.setMessage("修改订单失败");
                resultDTO.setSuccess(false);
                resultDTO.setMessageCode("500");
                return resultDTO;
            }
        } catch (BeansException ex) {
            LOGGER.error("AsnOrderController.updateAsnOrder error: {}", ex);
            throw new BusinessException(ex);
        }
    }

    /**
     * 删除订单
     *
     * @param wmsInboundOrderVOList
     * @return
     */
    @RequestMapping(value = "/deleteAsnOrder", method = RequestMethod.POST)
    @LogAnnotation(methods = "入库管理", modules = "删除订单")
    public ResultDTO deleteAsnOrder(@RequestBody List<WmsInboundOrderVO> wmsInboundOrderVOList) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            Vo2Bo converter = new Vo2Bo();
            List<WmsInboundOrderBO> wmsInboundOrderBOList = converter.convert(wmsInboundOrderVOList, WmsInboundOrderBO.class);
            asnOrderService.deleteAsnOrderByAsnOrderId(wmsInboundOrderBOList);
            resultDTO.setMessage("删除订单成功!");
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            return resultDTO;
        } catch (BeansException ex) {
            LOGGER.error("AsnOrderController.deleteAsnOrder error: {}", ex);
            resultDTO.setMessage("删除订单失败!");
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 根据运单号或者底盘号查询订单
     *
     * @param queryParam
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryByWaybillOrVin/{queryParam}")
    public ResultDTO queryByWaybillOrVin(@PathVariable("queryParam") String queryParam) throws Exception {
        ResultDTO resultDTO = new ResultDTO();
        try {
            WmsInboundOrderBO wmsInboundOrderBO = asnOrderService.queryByWaybillOrVin(queryParam);
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            resultDTO.setData(wmsInboundOrderBO);
            resultDTO.setMessage(null != wmsInboundOrderBO ? "查询成功!" : "无记录!");
            return resultDTO;
        } catch (BeansException ex) {
            LOGGER.error("WmsInboundOrderController.queryByWaybillOrVin error: {}", ex);
            resultDTO.setMessage("查询失败!");
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 质检收货/推送库位到app/推送退车到sap
     *
     * @param wmsInboundCheckVO
     * @return
     */
    @RequestMapping(value = "/submitAsnOrderCheck", method = RequestMethod.POST)
    @LogAnnotation(methods = "入库管理", modules = "入库订单质检")
    public ResultDTO submitAsnOrderCheck(@RequestBody WmsInboundCheckVO wmsInboundCheckVO) throws Exception {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        ResultDTO<Object> resultDTO = new ResultDTO();
        try {
            WmsInboundOrderDetailBO wmsInboundOrderDetailBO = new WmsInboundOrderDetailBO();
            WmsInboundAllocationBO wmsInboundAllocationBO = new WmsInboundAllocationBO();
            BeanUtils.copyProperties(wmsInboundCheckVO.getWmsInboundOrderDetailVOList().get(0), wmsInboundOrderDetailBO);
            //质检
            WmsInboundCheckBO wmsInboundCheckBO = new WmsInboundCheckBO();
            BeanUtils.copyProperties(wmsInboundCheckVO, wmsInboundCheckBO);
            Vo2Bo vo2Bo = new Vo2Bo();
            List<WmsInboundOrderDetailBO> wmsInboundOrderDetailBOList = vo2Bo.convert(wmsInboundCheckVO.getWmsInboundOrderDetailVOList(), WmsInboundOrderDetailBO.class);
            wmsInboundCheckBO.setWmsInboundOrderDetailBOList(wmsInboundOrderDetailBOList);
            List<WmsInboundAllocationBO> wmsInboundAllocationBOList = vo2Bo.convert(wmsInboundCheckVO.getWmsInboundAllocationVOList(), WmsInboundAllocationBO.class);
            wmsInboundCheckBO.setWmsInboundAllocationBOList(wmsInboundAllocationBOList);
            asnOrderCheckService.submitCheckAsnOrder(wmsInboundCheckBO);

            if (!Objects.isNull(wmsInboundCheckVO.getWmsInboundAllocationVOList())) {
                BeanUtils.copyProperties(wmsInboundCheckVO.getWmsInboundAllocationVOList().get(0), wmsInboundAllocationBO);
                //分配
                wmsStrategyService.addAllocation(wmsInboundAllocationBO);
            }

            //新增库存(入库确认的时候新增库存)
            //wmsInventoryService.addInventory(wmsInboundCheckBO);

            transactionManager.commit(status);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("质检成功");
            return resultDTO;
        } catch (Exception ex) {
            LOGGER.error("AsnOrderController.submitAsnOrderCheck error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("质检异常");
            transactionManager.rollback(status);
            return resultDTO;
        }
    }

    /**
     * 根据底盘号查询订单
     *
     * @param queryParam
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryByVin/{queryParam}")
    public ResultDTO queryByVin(@PathVariable("queryParam") String queryParam) throws Exception {
        ResultDTO resultDTO = new ResultDTO();
        try {
            WmsInboundOrderBO wmsInboundOrderBO = asnOrderService.queryByVin(queryParam);
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            resultDTO.setData(wmsInboundOrderBO);
            resultDTO.setMessage(null != wmsInboundOrderBO ? "查询成功!" : "无记录!");
            return resultDTO;
        } catch (BeansException ex) {
            LOGGER.error("WmsInboundOrderController.queryByVin error: {}", ex);
            resultDTO.setMessage("查询失败!");
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 库位调整
     *
     * @param wmsInboundAllocationVO
     * @return
     */
    @RequestMapping(value = "/locationAdjust")
    public ResultDTO locationAdjust(@RequestBody WmsInboundAllocationVO wmsInboundAllocationVO) {
        ResultDTO<Object> resultDTO = new ResultDTO<>();
        try {
            WmsInboundAllocationBO wmsInboundAllocationBO = new WmsInboundAllocationBO();
            BeanUtils.copyProperties(wmsInboundAllocationVO, wmsInboundAllocationBO);
            wmsAllocationService.updateAllocationByOdId(wmsInboundAllocationBO);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("库位调整成功");
            return resultDTO;
        } catch (Exception ex) {
            LOGGER.error("AsnOrderController.asnOrderCheck error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("库位调整异常");
            return resultDTO;
        }
    }

    /**
     * 可批量打印入库单二维码
     *
     * @param wmsInboundOrderVOList
     * @return
     * @throws WriterException
     * @throws IOException
     */
    @RequestMapping(value = "/printBarcode", method = RequestMethod.POST)
    public ResultDTO printBarcode(@RequestBody List<WmsInboundOrderVO> wmsInboundOrderVOList) throws WriterException, IOException {
        ResultDTO resultDTO = new ResultDTO();
        try {
            Vo2Bo converter = new Vo2Bo();
            List<WmsInboundOrderBO> wmsInboundOrderBOList = converter.convert(wmsInboundOrderVOList, WmsInboundOrderBO.class);
            List<AsnOrderDTO> asnOrderDetailList = asnOrderService.queryAsnOrderDetailListByAsnOrderId(wmsInboundOrderBOList);
            List<WmsPrintBarcodeVO> wmsPrintBarcodeVOList = Lists.newArrayList();
            //打印需要的参数
            String vin = "", locNo = "", destination = "", asnOrderBillNo = "";//底盘号,库位,目的地，运单号
            for (AsnOrderDTO asnOrderDetail : asnOrderDetailList) {
                asnOrderBillNo = asnOrderDetail.getOdWaybillNo();
                destination = asnOrderDetail.getOdDest();

                for (AsnOrderDetailDTO asnOrderDetailDTO : asnOrderDetail.getAsnOrderDetailDTOList()) {
                    locNo = asnOrderDetailDTO.getOddWhLocCode();
                    vin = asnOrderDetailDTO.getOddVin();
                }

                //String text = vin + ";" + locNo + ";" + destination + ";" + asnOrderBillNo+"  ";

                BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(vin, 60, 60);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(qrImageBuffer, "png", os);
                //Base64 base64 = new Base64();
                BASE64Encoder base64 = new BASE64Encoder();
                String base64Img = new String(base64.encode(os.toByteArray()));

                WmsPrintBarcodeVO wmsPrintBarcodeVO = new WmsPrintBarcodeVO();

                wmsPrintBarcodeVO.setBarcode(base64Img);
                wmsPrintBarcodeVO.setLocNo(locNo);
                wmsPrintBarcodeVO.setDestination(destination);
                wmsPrintBarcodeVO.setVin(vin);
                wmsPrintBarcodeVO.setAsnOrderBillNo(asnOrderBillNo);
                wmsPrintBarcodeVOList.add(wmsPrintBarcodeVO);
            }
            resultDTO.setSuccess(true);
            resultDTO.setMessage("获取打印数据成功");
            resultDTO.setMessageCode("200");
            resultDTO.setData(wmsPrintBarcodeVOList);
            return resultDTO;
        } catch (Exception ex) {
            LOGGER.error("AsnOrderController.printBarcode error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取打印数据失败");
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 入库确认--重庆库
     *
     * @param wmsInboundAllocationVO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/confirmInbound/{userId}", method = RequestMethod.POST)
    @LogAnnotation(methods = "入库管理", modules = "入库订单入库确认")
    public ResultDTO<Object> confirmInbound(@RequestBody WmsInboundAllocationVO wmsInboundAllocationVO, @PathVariable String userId) throws Exception {
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "入库成功");
        WmsInboundAllocationBO wmsInboundAllocationBO = new WmsInboundAllocationBO();
        BeanUtils.copyProperties(wmsInboundAllocationVO, wmsInboundAllocationBO);
        try {
            asnOrderService.updateConfirmInbound(wmsInboundAllocationBO, userId);
        } catch (BusinessException ex) {
            LOGGER.error("AsnOrderController.confirmInbound BusinessException: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
        } catch (Exception e) {
            LOGGER.error("AsnOrderController.confirmInbound error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }

    /**
     * 查询入库记录
     * <p>
     * 2018-1-11 新增取消入库功能
     * 1.调整入库记录查询列表逻辑(取消入库记录可以查到,但是不展示之前的入库记录的时间)
     * 2.退库的数据是可以正常展示以前的入库记录及时间
     * 2018-1-22 新需求 入库记录查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段；
     * 2018-3-16 入库记录查询(君马)增加物料名称条件查询
     * </p>
     *
     * @param jsonStr 参数封装json串
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/inboundRecord", method = RequestMethod.POST)
    public ResultDTO<Object> inboundRecord(@RequestBody String jsonStr, HttpServletRequest request) throws Exception {
        LOGGER.info("WmsInboundOrderController.inboundRecord jsonStr: {}", jsonStr);
        if (Objects.equals(jsonStr, null)) {
            throw new Exception("参数为null");
        }
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, "查询入库记录成功");
        try {
            Map<String, Object> paramMap = JSON.parseObject(jsonStr);
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            paramMap.put("odWhCode", whCode);
            resultDTO.setData(asnOrderService.queryInboundRecord(paramMap));
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.inboundRecord BusinessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            LOGGER.error("WmsInboundOrderController.inboundRecord error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询入库记录异常");
        }
        return resultDTO;
    }

    /**
     * 入库记录导出功能
     * <p>
     * 2018-1-22 新需求 (君马库)入库记录查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段；
     * </p>
     *
     * @param dto 参数封装
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/recordImportExcel", method = RequestMethod.GET)
    public ResultDTO<Object> recordImportExcel(WmsRecordsImportExcelDTO dto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOGGER.info("WmsInboundOrderController.recordImportExcel param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "导出记录成功");
        try {
            if (Objects.equals(dto, null)) {
                throw new BusinessException("传入参数为空!");
            }
            if (StringUtils.isBlank(dto.getWhCode())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录账户未绑定对应仓库");
                return resultDTO;
            }
            if (StringUtils.isBlank(dto.getUserId())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("未登录");
                return resultDTO;
            }
            wmsInboundAsnService.updateInboundImportExcel(dto, request, response);
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.recordImportExcel error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            LOGGER.error("WmsInboundOrderController.recordImportExcel error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("导出记录异常");
        }
        return resultDTO;
    }

    /**
     * 判断导出的数据量
     *
     * @param dto 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/queryRecordCount", method = RequestMethod.GET)
    public ResultDTO<Object> queryRecordCount(WmsRecordsImportExcelDTO dto) {
        LOGGER.info("WmsInboundOrderController.recordImportExcel param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "导出记录成功");
        try {
            if (Objects.equals(dto, null)) {
                throw new BusinessException("传入参数为空!");
            }
            if (StringUtils.isBlank(dto.getWhCode())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录账户为绑定对应仓库");
                return resultDTO;
            }
            if (StringUtils.isBlank(dto.getUserId())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("未登录");
                return resultDTO;
            }
            Integer integer = wmsInboundAsnService.countInboundRecord(dto);
            if (integer == null || integer <= 0) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("没有对应的数据");
                return resultDTO;
            }
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.recordImportExcel error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            LOGGER.error("WmsInboundOrderController.recordImportExcel error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("导出记录异常");
        }
        return resultDTO;
    }


    /**
     * 收货质检 - 君马库
     * <p>
     * 2018-1-9 新需求:君马闸门开启入场
     * </p>
     * 2018-1-14  bugfix 事务调整
     *
     * @param wmsInboundOrderVO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/deliverToConfirm", method = RequestMethod.POST)
    public ResultDTO<Object> deliverToConfirm(@RequestBody WmsInboundOrderVO wmsInboundOrderVO) {
        LOGGER.info("WmsInboundOrderController.deliverToConfirm wmsInboundOrderVO: {}", wmsInboundOrderVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "收货质检入库成功");
        try {
            if (wmsInboundOrderVO == null
                    || StringUtils.isBlank(wmsInboundOrderVO.getOddVin())
                    || !StringUtils.isNumeric(wmsInboundOrderVO.getUserId())) {
                throw new BusinessException("参数为空!");
            }
            //业务层处理数据  aop事务增强；
            //DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
            //defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            //TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

            String vin = wmsInboundOrderVO.getOddVin();
            if (StringUtils.isBlank(vin)) {
                throw new BusinessException("传入车架号为空!");
            }
            //回车字符替换
            if (vin.endsWith("\n")) {
                vin = vin.replaceAll("\n", "");
            }

            AsnOrderDTO result = wmsStrategyService.saveAllcationByExtraForJunMa(vin, wmsInboundOrderVO.getUserId());
            LOGGER.info("WmsInboundOrderController.AsnOrderDTO: {}", JSONObject.toJSONString(result));
            if (result != null) {
                List<AsnOrderDetailDTO> asnOrderDetailDTOList = result.getAsnOrderDetailDTOList();
                if (CollectionUtils.isNotEmpty(asnOrderDetailDTOList)) {
                    AsnOrderDetailDTO asnOrderDetailDTO = asnOrderDetailDTOList.get(0);
                    if (asnOrderDetailDTO != null) {
                        resultDTO.setData(asnOrderService.getInBoundInfoByVin(asnOrderDetailDTO.getOddVin()));
                    }
                }
                //推送库位到app 及 打印二维码到页面
                wmsLocationService.updateSendToAPPAndPrintCode(result, wmsInboundOrderVO.getUserId());
                //2018-1-9  新增库位分配完成后开启闸门
                new Thread(()->{
                    try {
                        gateControllerService.updateJmGateIn(result);
                    }  catch (BusinessException be) {
                        LOGGER.error("WmsInboundOrderController.deliverToConfirm.updateJmGateIn businessException: {}", be);
                    }catch (Exception ex) {
                        LOGGER.error("WmsInboundOrderController.deliverToConfirm.updateJmGateIn error: {}", ex);
                    }
                }).start();
            }
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.deliverToConfirm businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsInboundOrderController.deliverToConfirm error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }

    /**
     * 收货质检 - 君马库
     *
     * @return
     */
    @RequestMapping(value = "/deliverToConfirm2/{vin}", method = RequestMethod.POST)
    public ResultDTO<Object> getInBoundInfoByVin2(@PathVariable String vin) {
        LOGGER.info("WmsInboundOrderController.getInBoundInfoByVin2 wmsInboundOrderVO: {}", vin);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取数据成功");
        try {
            WmsInboundOrderDTO wmsInboundOrderDTO = asnOrderService.updateToInConfirm2(vin);
            if (wmsInboundOrderDTO == null) {
                throw new BusinessException("无法找到车辆信息");
            }
            resultDTO.setData(wmsInboundOrderDTO);
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.getInBoundInfoByVin2 businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsInboundOrderController.getInBoundInfoByVin2 error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取数据失败");
        }
        return resultDTO;
    }

    /**
     * 根据车架号获取信息
     *
     * @return
     */
    @RequestMapping(value = "/getInBoundInfoByVin/{vin}", method = RequestMethod.GET)
    public ResultDTO<Object> getInBoundInfoByVin(@PathVariable String vin) {
        LOGGER.info("WmsInboundOrderController.getInBoundInfoByVin wmsInboundOrderVO: {}", vin);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取数据成功");
        try {
            resultDTO.setData(asnOrderService.getInBoundInfoByVin(vin));
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.getInBoundInfoByVin businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsInboundOrderController.getInBoundInfoByVin error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取数据失败");
        }
        return resultDTO;
    }


    /**
     * <p>
     * 2018/1/8  新需求-取消入库
     * 根据车架号,进行取消入库操作--需要同步tms
     * 防止入库邮件重复发送
     * </p>
     *
     * @return 返回值resultDto
     */
    @RequestMapping(value = "/updateCancleInbound", method = RequestMethod.POST)
    public ResultDTO<Object> updateCancleInbound(@RequestBody WmsInboundOrderDTO dto, HttpServletRequest request) {
        LOGGER.info("WmsInboundOrderController.updateCancelInbound WmsInboundOrderDTO: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "操作成功");
        try {
            String userId = request.getHeader("userId");
            String whCode = request.getHeader("whCode");
            dto.setWhCode(whCode);
            dto.setUserId(userId);
            asnOrderService.updateCancelInbound(dto);
        } catch (BusinessException e) {
            LOGGER.error("WmsInboundOrderController.updateCancelInbound businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsInboundOrderController.updateCancelInbound error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }

}
